package com.example.sunsg.okhttptest.util;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;


import com.example.sunsg.okhttptest.bean.KeyValue;

import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

/**
 * Created by sunsg on 15/9/11.
 */
public class SecretUtil {
    /**加密秘钥*/
    public static final String SECRET = "MIIEowIBAAKCAQEAwbEIlVOexfkIQkYT9Us7iukU02PQsLZ9OHxxvWJaXCjKhdht";
    public static final String DEBUG_SECRET = "S9s3tNUbibkP/5ZZwAjhNLH+oy0kGLgx/zyEQjSttkRYiOuUv7LAMI7FnhzfwAlp";

    /**
     * 增加秘钥参数 TODO 更优雅的机制，httpfilter？
     *
     * @param list
     */
    public static String getSecretSign(List<KeyValue> list, Context context) {
        StringBuilder sb = new StringBuilder();
        if(list == null || list.size() == 0){
            return "";
        }
        Collections.sort(list, comparator);

        Iterator<KeyValue> iterator = list.iterator();
        while (iterator.hasNext()) {
            KeyValue np = iterator.next();
            String name = np.getKey();
            String value = np.getValue();
            if (TextUtils.isEmpty(name) || TextUtils.isEmpty(value)) {
                iterator.remove();
                continue;
            }
            try {
                value = EncodeUtils.urlEncode(value);
                sb.append(name).append("=").append(value);
                if (iterator.hasNext()) {
                    sb.append("&");
                }
            } catch (UnsupportedEncodingException e) {
//                Logger.e(e);
            }
        }

        sb.append(PackageUtils.getAppVersionName(context)).append(SECRET);
//        if(Logger.isDebugable()){
//            Logger.d("TAG", "拼接字符串 = " + sb.toString());
//                Log.i("test","sb.tostring = "+sb.toString());
//        }
        String sign = EncodeUtils.encodeMD5(sb.toString());
        list.add(new KeyValue("sign", sign));

//        if(Logger.isDebugable()){
            Log.d("TAG", "加密开始===========");
            for(KeyValue np : list){
                Log.d("TAG", np.getKey() + " = " +np.getValue());
            }
            Log.d("TAG", "加密结束===========");
//        }
        return sign;
    }

    /**
     * 参数排序比较器
     */
    static Comparator<KeyValue> comparator = new Comparator<KeyValue>() { // solution than making method synchronized
        @Override
        public int compare(KeyValue p1, KeyValue p2) {
            return p1.getKey().compareTo(p2.getKey());
        }
    };
}
